package org.techmore.biz;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.techmore.R;
import org.techmore.utils.DownloadNoStoreHandler;
import org.techmore.utils.ImageDownloadReturnPathHandler;
import org.techmore.utils.PropertiesUtil;
import org.techmore.vo.LBSStoreVO;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;

public class CouponMapActivityDataHandler {
	
	private static CouponMapActivityDataHandler couponMapActivityDataHandler = new CouponMapActivityDataHandler();
	
	public static CouponMapActivityDataHandler getInstance(){
		return couponMapActivityDataHandler;
	}
	
	private SAXParserFactory factory = null;
	private SAXParser parser = null;
	
	private LBSStoreVO lbsStoreVO = null;
	private ArrayList<LBSStoreVO> lbsStoreVOs = null;
	private Handler storeHandler = null;
	
	private Context context;
	private MapView mapView;
	private List<Overlay> overlays;
	private View mapPopView;
	
	public void getLBSStoreByUrl(Context context,MapView mapView,List<Overlay> overlays,View mapPopView,double rangeD,String latitude,String longitude){
		
		this.context = context;
		this.mapView = mapView;
		this.overlays = overlays;
		this.mapPopView = mapPopView;
		
		lbsStoreVOs = new ArrayList<LBSStoreVO>();
		
		String urlPath = PropertiesUtil.getInstance().getValue("qr_map_seach")+"&longitude="+longitude+"&latitude="+latitude+"&range="+String.valueOf(rangeD);
		
//		System.out.println(urlPath);
		
		try {
			factory = SAXParserFactory.newInstance();
			parser = factory.newSAXParser();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			Log.e("CouponMapActivityDataHandler:", e.getMessage());
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			Log.e("CouponMapActivityDataHandler:", e.getMessage());
		}
		
		storeHandler = new Handler(Looper.myLooper()){
			public void handleMessage(android.os.Message msg) {
				int sign = msg.what;
    			if(sign == 1){
    				String uri = String.valueOf(msg.obj);
        			try {
						parser.parse(new ByteArrayInputStream(uri.getBytes()), new LBSStoreVO_Handler());
					} catch (SAXException e) {
						Log.e("CouponMapActivityDataHandler:", e.getMessage());
					} catch (IOException e) {
						Log.e("CouponMapActivityDataHandler:", e.getMessage());
					}
					
					for(LBSStoreVO vo : lbsStoreVOs){
						adapterMap(vo);
					}
					
    			}
			};
		};
		
		storeHandler.post(new DownloadNoStoreHandler(urlPath, storeHandler, 1));
		
	}
	
	private void adapterMap(final LBSStoreVO lbsStoreVO){
		if(null==lbsStoreVO.getMapIconUrl() || "".equals(lbsStoreVO.getMapIconUrl())){
			prepareCouponMapOverlayView(lbsStoreVO,context.getResources().getDrawable(R.drawable.shopping_car));
		}else{
			Handler subjectImageIco = new Handler(Looper.myLooper()){
				@Override
				public void handleMessage(Message msg) {
    				String imagePath = (String) msg.obj;
    				prepareCouponMapOverlayView(lbsStoreVO,Drawable.createFromPath(imagePath));
				}
			};
			
			subjectImageIco.post(new ImageDownloadReturnPathHandler(lbsStoreVO.getMapIconUrl(), subjectImageIco, 
					lbsStoreVO.getMapIconUrl().substring(lbsStoreVO.getMapIconUrl().lastIndexOf("/"), lbsStoreVO.getMapIconUrl().length()),
					24,24));
		}
	}
	
	private void prepareCouponMapOverlayView(LBSStoreVO lbsStoreVO,Drawable defaultMarker){
		GeoPoint geo = new GeoPoint((int)(Double.valueOf(lbsStoreVO.getLatitude())*1E6), (int)(Double.valueOf(lbsStoreVO.getLongitude())*1E6));
		OverlayItem overlayitem = new OverlayItem(geo, lbsStoreVO.getSubject()+"##"+lbsStoreVO.getSerNO(),
				geo.getLatitudeE6()+"##"+geo.getLongitudeE6());
		CouponMapOverlayView couponMapOverlayView = new CouponMapOverlayView(context, mapView, mapPopView,defaultMarker);
		couponMapOverlayView.addOverlay(overlayitem);
    	overlays.add(couponMapOverlayView);
	}
	
	
	
	//  <store serNo="201104180001" subject="商家測試" longitude="121.559834" latitude="25.091075" mapIconUrl="" /> 
	public class LBSStoreVO_Handler extends DefaultHandler{
		public LBSStoreVO_Handler(){}
		@Override
		public void startDocument() throws SAXException {
			super.startDocument();
		}
		@Override
		public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
			super.startElement(uri, localName, qName, attributes);
			
			if("store".equals(qName) || "store".equals(localName) ){
				lbsStoreVO = new LBSStoreVO();
				lbsStoreVO.setSerNO(attributes.getValue("serNo"));
				lbsStoreVO.setSubject(attributes.getValue("subject"));
				lbsStoreVO.setLongitude(attributes.getValue("longitude"));
				lbsStoreVO.setLatitude(attributes.getValue("latitude"));
				lbsStoreVO.setMapIconUrl(attributes.getValue("mapIconUrl"));
				lbsStoreVOs.add(lbsStoreVO);
			}
		}
		@Override
		public void endDocument() throws SAXException {
			super.endDocument();
		}
		@Override
		public void endElement(String uri, String localName, String qName) throws SAXException {
			super.endElement(uri, localName, qName);
			if("store".equals(qName) || "store".equals(localName)){
				lbsStoreVO = null;
			}
		}
		@Override
		public void characters(char[] ch, int start, int length) throws SAXException {
		}
	}

}
